﻿using System;
using System.Linq;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;
using Native.XQ.SDK;
using Native.XQ.SDK.Event.EventArgs;
using Native.XQ.SDK.Interfaces;

namespace Native.XQ.Core.Events
{
    public class Event_GroupMessage : IXQGroupMessage
    {
        public void GroupMessage(object sender, XQAppGroupMsgEventArgs e)
        {
            //创建赛马
            if (e.Message.Text == "创建赛马")
            {
                if (CreateHR(e.FromGroup.Id))
                {
                    e.FromGroup.SendMessage(e.RobotQQ, "创建赛马比赛成功\n输入 加入赛马 [马的Emoji] 即可加入赛马\nEmoji不填写则为默认的马");
                }
                else
                {
                    e.FromGroup.SendMessage(e.RobotQQ, "创建赛马比赛失败：已经存在这个赛马比赛!");
                }
            }
            //加入赛马 [🐎]

            if (e.Message.Text.StartsWith("加入赛马") )
            {
                var horse = e.Message.Text.Replace("加入赛马", "").Trim();
                var r = false;
                if (horse == string.Empty)
                {
                    //无马，默认
                    r = JoinRace(e.FromGroup.Id, e.FromQQ.Id);
                }
                else
                {
                    r = JoinRace(e.FromGroup.Id, e.FromQQ.Id, horse);
                }

                if (!r)
                {
                    e.FromGroup.SendMessage(e.RobotQQ, $"[@{e.FromQQ.Id}] 加入赛马失败:比赛未创建/比赛已开始/您已加入比赛");
                }
                else
                {
                    e.FromGroup.SendMessage(e.RobotQQ, $"[@{e.FromQQ.Id}] 加入赛马成功\n堵上马儿性命的一战即将开始！");
                    if (HorseRace.Races[e.FromGroup.Id].Horses.Count >= 6)
                    {
                        ProcessRace(e.XQAPI, e.RobotQQ, e.FromGroup.Id);
                    }
                }
            }
            //开始赛马/人满自动赛马

            if (e.Message.Text == "加入赫尔")
            {
                var r = false;
                    //无马，默认
                r = JoinRace(e.FromGroup.Id, e.FromQQ.Id,"🐖");


                if (!r)
                {
                    e.FromGroup.SendMessage(e.RobotQQ, $"[@{e.FromQQ.Id}] 加入赛马失败:比赛未创建/比赛已开始/您已加入比赛");
                }
                else
                {
                    e.FromGroup.SendMessage(e.RobotQQ, $"[@{e.FromQQ.Id}] 加入赛马成功\n堵上马儿性命的一战即将开始！");
                    if (HorseRace.Races[e.FromGroup.Id].Horses.Count >= 6)
                    {
                        ProcessRace(e.XQAPI, e.RobotQQ, e.FromGroup.Id);
                    }
                }
            }

            if (e.Message.Text == "开始赛马")
            {
                if (!ProcessRace(e.XQAPI, e.RobotQQ, e.FromGroup.Id))
                {
                    e.FromGroup.SendMessage(e.RobotQQ, "赛马开启失败:比赛不存在/比赛以开启/比赛马儿数量不足");
                }
            }
            //赛马逻辑
            //蜜汁事件发生
            //赛马结果
        }

        public bool CreateHR(string group)
        {
            if (HorseRace.Races.ContainsKey(group))
            {
                return false;//已存在一个群赛马场
            }
            //否则添加一个赛马场
            HorseRace.Races.Add(group, new RaceGroud());
            return true; // 创建成功
        }

        /// <summary>
        /// 以默认的🐎加入赛马场
        /// </summary>
        /// <param name="group"></param>
        /// <param name="qq"></param>
        /// <param name="display"></param>
        /// <returns></returns>
        public bool JoinRace(string group, string qq, string display = "[emoji=F09F90B4]")
        {
            if (!HorseRace.Races.ContainsKey(group))
            {
                return false;
            }

            if (HorseRace.Races[group].Horses.FindIndex(h => h.OwnerQQ == qq) != -1)
            {
                //已经拥有此数据
                return false;
            }

            if (HorseRace.Races[group].isOn)
            {
                //赛马已开始
                return false;
            }
            if (display.Contains("[pic="))
            {
                return false;
            }
            if (display.Length > 24)
            {
                return false;
            }
            if (!display.StartsWith("[") && display.Length > 4)
                return false;

            HorseRace.Races[group].Horses.Add(new Horse() { Display = display, OwnerQQ = qq });
            return true;
        }

        public bool ProcessRace(XQAPI api, string robot, string group)
        {
            if (!HorseRace.Races.ContainsKey(group))
                return false;
            if (HorseRace.Races[group].isOn)
                return false;
            if (HorseRace.Races[group].Horses.Count <= 3)
                return false;
            Task.Factory.StartNew(async () =>
            {
                var badend = 0;
                HorseRace.Races[group].isOn = true;
                //开启赛马
                var ground = HorseRace.Races[group];
                StringBuilder sb = new StringBuilder();

                var longstr = new string(HorseRace.StepDisplay, HorseRace.AllLong);
                ground.Horses.ForEach(s =>
                {
                    var _mestr = longstr;
                    _mestr = _mestr.Insert(_mestr.Length, s.Display);
                    sb.AppendLine(_mestr);
                });
                api.SendGroupMessage(robot, group, sb.ToString());
                sb.Clear();

                bool needContinue = false;
                switch (HorseRace.RaceMode)
                {
                    case RaceMode.OneWin:
                        needContinue = ground.Horses.FindIndex(s => s.Step == HorseRace.AllLong) == -1;
                        break;

                    case RaceMode.AllWin:
                        needContinue = !ground.Horses.All(s => s.Step == HorseRace.AllLong);
                        break;

                    case RaceMode.KillMode:
                        break;

                    default:
                        return;
                }

                while (needContinue)
                {
                    await Task.Delay(HorseRace.Interval * 1000);

                    //处理每只马
                    foreach (var item in ground.Horses.FindAll(s => !s.died))
                    {
                        item.lastStep = new Random(Guid.NewGuid().GetHashCode()).Next(HorseRace.MinStep, HorseRace.MaxStep + 1);
                        item.Step += item.lastStep;
                        if (item.Step > HorseRace.AllLong)
                        {
                            item.Step = HorseRace.AllLong;
                        }
                    }

                    //魔法时间+语句
                    if (new Random().NextDouble() <= HorseRace.RandomEvent)
                    {
                        //被魔法选中的马
                        var index = new Random(Guid.NewGuid().GetHashCode()).Next(0, ground.Horses.Count - 1);

                        if (!ground.Horses[index].died)
                        {
                            //羊驼 [Face185.gif]
                            //触发随机事件
                            int _event = new Random(Guid.NewGuid().GetHashCode()).Next(0, 16);
                            var needbreak = false;
                            switch (_event)
                            {
                                case 0:
                                    //哈!空间传送
                                    ground.Horses[index].Step += 3;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%获得了白井黑子的力量，往前空间跳跃了3格!");
                                    break;

                                case 1:
                                    //沉迷Phub
                                    ground.Horses[index].Step -= ground.Horses[index].lastStep + 1;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%沉迷PHub，后退了1格");
                                    break;

                                case 2:
                                    //击中
                                    ground.Horses[index].died = true;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%被天上的飞机击中了，不幸离开了战场");
                                    break;

                                case 3:
                                    //心脏病
                                    ground.Horses[index].died = true;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%突发心脏病，不幸离开了战场");
                                    break;

                                case 4:
                                    //掉入二次元
                                    ground.Horses[index].Step -= ground.Horses[index].lastStep + 3;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%掉入了二次元，沉迷其中，无法自拔，后退了3格");
                                    break;

                                case 5:
                                    //ba！ba！
                                    ground.Horses[index].Step += 2;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%成为了脚艺马，速度更快了!");
                                    break;

                                case 6:
                                    //游乐王子
                                    ground.Horses[index].Step += 1;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%吃了游乐王子卖的茶叶，吓得前进了1格!");
                                    break;

                                case 7:
                                    //我命由我不由天
                                    ground.Horses[index].Step = 0;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%觉得我命由我不由天，跑回了起点！");
                                    break;

                                case 8:
                                    //诡计
                                    ground.Horses.ForEach(s => { if (s != ground.Horses[index]) { s.Step = 0; } });
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%智商增加了，施了诡计使得除了他之外的选手退回了起点!");
                                    break;

                                case 9:
                                    //I am free
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的{ground.Horses[index].Display}%大喊\"我免费了!\"并笑着离开了赛场");
                                    ground.Horses.Remove(ground.Horses[index]);
                                    break;

                                case 10:
                                    //撞击！
                                    var index2 = new Random(Guid.NewGuid().GetHashCode()).Next(0, ground.Horses.Count - 2);
                                    if (index2 == index)
                                    {
                                        index2++;
                                    }
                                    var horse2 = ground.Horses[index2];
                                    ground.Horses[index2].Step -= ground.Horses[index2].lastStep;
                                    ground.Horses[index2].TempDisplay = "[眩晕]" + horse2.Display;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%撞了一下[@{horse2.OwnerQQ}]的{horse2.Display}\n对方选手负伤了!");
                                    break;

                                case 12:
                                    //天降金钱
                                    //[emoji=F09F92B0]
                                    ground.Horses[index].TempDisplay = "[emoji=F09F92B0]" + ground.Horses[index].Display;
                                    ground.Horses[index].Step -= ground.Horses[index].lastStep;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%发现了地上的女装币，停下了脚步");
                                    break;

                                case 13:
                                    //蔡徐坤的篮球
                                    ground.Horses[index].Step += 2;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%发现了赛场上观赛的菜许坤，赶紧加速跑走了(步数+2)");
                                    break;

                                case 14:
                                    //终焉律者
                                    badend = 1;
                                    needContinue = false;
                                    ground.Horses.ForEach(s => s.died = true);
                                    ground.Horses[index].TempDisplay = "[终焉律者]" + ground.Horses[index].Display;
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%被崩坏能侵蚀，成为了终焉律者，毁灭了世界");
                                    needbreak = true;
                                    break;
                                case 15:
                                    //克隆
                                    var h = ground.Horses[index];
                                    ground.Horses.Add(new Horse() { OwnerQQ=h.OwnerQQ,Display="[克隆体]"+h.Display} );
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%被实验人员抓走，克隆了一只克隆体加入比赛");
                                    break;
                                case 16:
                                    //策划司马
                                    ground.Horses[index].Step -= ground.Horses[index].lastStep;
                                    ground.Horses[index].TempDisplay ="[应聘策划]";
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%去应聘肝坏3的策划，牺牲自己的时间拯救了无数玩家!暂时停止了前进。");
                                    break;
                                case 17:
                                    //策划司马
                                    ground.Horses[index].Step -= ground.Horses[index].lastStep;
                                    ground.Horses[index].TempDisplay = "[应聘策划]";
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%去应聘肝坏3的策划，牺牲自己的时间拯救了无数玩家!暂时停止了前进。");
                                    break;

                                case 18:
                                    //策划司马
                                    ground.Horses[index].Step = new Random(Guid.NewGuid().GetHashCode()).Next(0,HorseRace.AllLong);
                                    sb.AppendLine($"[@{ground.Horses[index].OwnerQQ}]的%马儿%失忆了，随机进入了一格");
                                    break;
                            }
                            sb.Replace("%马儿%", ground.Horses[index].Display);
                            if (needbreak)
                                break;


                        }
                    }
                    //处理步数异常
                    foreach (var item in ground.Horses)
                    {
                        if (item.Step > HorseRace.AllLong)
                        {
                            item.Step = HorseRace.AllLong;
                        }
                        if (item.Step < 0)
                        {
                            item.Step = 0;
                        }
                    }

                    //步数语句
                    ground.Horses.ForEach(s =>
                    {
                        s.lastStep = 0;//清除步数缓存
                        var _mestr = longstr;
                        //TempDisplay用来给马儿加一下前缀后缀
                        if (s.TempDisplay == "")
                        {
                            s.TempDisplay = s.Display;
                        }
                        _mestr = _mestr.Insert(HorseRace.AllLong - s.Step, s.TempDisplay);
                        s.TempDisplay = "";
                        sb.AppendLine(_mestr.Replace("%马儿%", s.Display));
                    });

                    //发送
                    api.SendGroupMessage(robot, group, sb.ToString());
                    sb.Clear();

                    switch (HorseRace.RaceMode)
                    {
                        case RaceMode.OneWin:
                            needContinue = ground.Horses.FindIndex(s => s.Step == HorseRace.AllLong) == -1;
                            break;

                        case RaceMode.AllWin:
                            needContinue = !ground.Horses.All(s => s.Step == HorseRace.AllLong);
                            break;

                        case RaceMode.KillMode:
                            break;

                        default:
                            return;
                    }

                    
                }

                //结束
                if (badend == 0)
                {
                    ground.Horses.ForEach(h =>
                    {
                        if (h.Step >= HorseRace.AllLong)
                        {
                        //已到达终点
                        sb.AppendLine($"[@{h.OwnerQQ}]的{h.Display}成功达到了终点，获得了胜利");
                        }
                        else
                        {
                            if (h.died)
                            {
                                sb.AppendLine($"[@{h.OwnerQQ}]的{h.Display}没能抵达终点，你的{h.Display}已经在中途死亡");
                            }
                            else
                            {
                                sb.AppendLine($"[@{h.OwnerQQ}]的{h.Display}没能抵达终点，你的{h.Display}被送进了屠宰场");
                            }
                        }
                    });
                }
                else
                {
                    switch (badend)
                    {
                        case 1:
                            sb.AppendLine("—— 人类，你们的存在就是错误！");
                            sb.AppendLine("无数的崩坏能倾泻开来，世界在律者的力量之下毁灭了");
                            break;
                    }
                }
                api.SendGroupMessage(robot, group, sb.ToString());
                HorseRace.Races.Remove(group);
            });
            return true;
        }
    }
}